<template>
  <view class="follow-page">
    <view class="status-bar"></view>
    <view class="dark">
      <!-- 顶部导航 -->
      <follow-header :current-tab="currentTab"></follow-header>
      <!-- 横向滑动关注列表 -->
      <follow-list
        ref="followListRef"
        :follow-lists="followList"
        @load-follow-video-data="loadFollowVideoData"
      ></follow-list>
      <!-- 关注用户视频流 -->
      <view class="follow-videos-container">
        <view ref="scrollbarRef" @scroll="handleScroll" class="scroll-view">
          <!-- 添加 scroll 事件监听 -->
          <view v-if="hasFollowVideo">
            <view
              class="videoView"
              v-for="(videoItem, index) in followVideoList"
              :key="index"
              ref="videoRefs"
            >
              <follow-video
                :video="videoItem"
                ref="videoPlayerRefs"
                :index="index"
                @toggle-sound-all="toggleSoundAll"
              />
            </view>
          </view>
          <view v-else class="no-data">没有数据</view>
        </view>
      </view>
    </view>
    <!-- 底部导航 -->
    <tab></tab>
  </view>
</template>

<script>
  import { followsData as defaultFollows } from "@/data-test/follow-data";
  import { followVideosData } from "@/data-test/follow-video-data";

  import tab from "@/components/tab.vue";
  import followHeader from "@/components/follow/follow-header.vue";
  import followList from "@/components/follow/follow-list.vue";
  import followVideo from "@/components/follow/follow-video.vue";
  import api from "@/API";
  let timer = null;
  export default {
    components: {
      tab,
      followHeader,
      followList,
      followVideo,
    },
    data() {
      return {
        followList: [],
        isLoading: false,
        error: null,
        isRefreshing: false,
        followVideoList: [],
        firstUserId: "",
        currentTab: "follow",
        visibleIndex: 0,
      };
    },
    computed: {
      hasFollowVideo() {
        return this.followVideoList && this.followVideoList.length > 0;
      },
    },
    async created() {
      await this.loadFollowData(() => {
        if (this.followList.length > 0) {
          this.$refs.followListRef.clickFollow(this.firstUserId, 0); // 调用子组件的方法
        }
      });
    },
    methods: {
      async loadFollowData(callback) {
        this.isLoading = true;
        this.error = null;
        const resolveFollows = (follows, callback) => {
          this.followList = follows;
          this.firstUserId = this.followList[0].id;
          this.isLoading = false;
          callback();
        };
        api.follow
          .getFollows()
          .then((res) => {
            resolveFollows(res.data, callback);
          })
          .catch((err) => {
            if (!err.data && err.statusCode === 500) {
              resolveFollows(defaultFollows, callback);
            }
          });
      },
      loadFollowVideoData(user_id) {
        api.follow
          .getFollowVideos()
          .then((res) => {
            this.followVideoList = res.data[user_id];
          })
          .catch((err) => {
            if (!err.data && err.statusCode === 500) {
              this.followVideoList = followVideosData[user_id];
            }
          });
      },
      toggleSoundAll() {
        this.$refs.videoPlayerRefs.forEach((player) => {
          if (player && player.videoEl.muted) {
            player.videoEl.muted = false;
            player.soundTip.classList.add("tw-hidden");
          }
        });
      },
      handleScroll(event) {
        clearTimeout(timer);
        timer = setTimeout(() => {
          const { scrollTop } = event;
          // #ifdef H5
          const videoContainerHeight = this.$refs.videoRefs[0].$el.offsetHeight;
          // 计算当前可见的视频索引
          const visibleIndex = Math.floor(
            (scrollTop + 170) / videoContainerHeight
          );
          this.visibleIndex = visibleIndex;
          // #endif
        }, 100);
      },
      initializeVideoPlayers() {
        this.$nextTick(() => {
          this.$refs.videoPlayerRefs.forEach((player) => {
            if (player && player.initVideoContext) {
              player.initVideoContext();
            }
          });
          // #ifdef H5
          if (this.$refs.scrollbarRef.setScrollTop) {
            this.$refs.scrollbarRef.setScrollTop(0);
          }
          // #endif
        });
      },
    },
    watch: {
      visibleIndex() {
        // 停止所有视频播放
        this.$refs.videoPlayerRefs.forEach((player) => {
          if (player && player.pauseVideo) {
            player.pauseVideo();
          }
        });

        // 播放当前可见的视频
        const visibleVideoPlayer =
          this.$refs.videoPlayerRefs[this.visibleIndex];
        if (visibleVideoPlayer && visibleVideoPlayer.playVideo) {
          visibleVideoPlayer.playVideo();
        }
      },
      followVideoList: {
        handler(newVal, oldVal) {
          this.initializeVideoPlayers();
        },
        deep: true,
      },
    },
    beforeUpdate() {},
    updated() {},
  };
</script>

<style scoped>
  .follow-page {
    /* height: 100vh; */
    display: flex;
    flex-direction: column;
    position: relative;
  }

  /* .follow-header {
    height: 44px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-bottom: 1px solid #333;
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 20;
  } */

  .header-title {
    font-size: 18px;
    font-weight: bold;
    color: #fff;
  }

  .follow-lists {
    display: flex;
    /* position: fixed; */
    top: 45px;
    left: 0; /* 左侧固定导航 */
    right: 0; /* 容器占据整个视口的宽度*/
    white-space: nowrap;
    padding: 10px 0 0 0;
    background-color: #000;
    overflow-x: auto;
    z-index: 10;
    /* flex: 0 0 auto; */
  }
  .follow-lists::-webkit-scrollbar {
    background-color: #000;
  }

  .scrollbar-wrapper {
    height: 100%;
    overflow-x: auto;
    overflow-y: hidden;
  }
  .scrollbar-view {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    height: 100%;
  }
  .user-avatar {
    width: 50px;
    height: 50px;
    border-radius: 25px;
    margin-bottom: 5px;
  }
  .user-focus {
    border: 3px solid red;
  }

  .scrollbar-flex-content {
    display: flex;
    min-width: max-content; /* 确保内容超出容器时可以滚动 */
  }
  .scrollbar-demo-item {
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin: 10px;
    text-align: center;
    border-radius: 4px;
    min-width: 55px;
  }
  .follow-videos-container {
    background-color: #171827;
    /* 允许内容区域自动扩展 */
    flex: 1 1 auto;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    /* #ifdef MP-WEIXIN */
    height: calc(100vh - 240px);
    /* #endif */
    /* #ifdef H5 */
    height: calc(100vh - 220px);
    /* #endif */
  }
  .follow-videos-container::-webkit-scrollbar {
    display: none;
  }
  .scroll-view {
    height: 100%;
  }
  .no-data {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    color: #909399;
    font-size: 16px;
  }
</style>
